package com.silver.weibo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.silver.weibo.dao.LabelMapper;
import com.silver.weibo.entity.*;
import com.silver.weibo.entity.dto.BlogListDTO;
import com.silver.weibo.entity.vo.BlogDetailVO;
import com.silver.weibo.entity.vo.UserVO;
import com.silver.weibo.server.BlogService;
import com.silver.weibo.server.CommentService;
import com.silver.weibo.server.UserService;
import com.silver.weibo.utils.MyContextUtil;
import com.silver.weibo.utils.PageUtil;
import com.silver.weibo.utils.UploadImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/blog")
public class BlogController {

    private final LabelMapper labelMapper;
    private final UserService userService;
    private final BlogService blogService;
    private final CommentService commentService;
    private final UploadImage uploadImage;
    //private static final Logger logger = LogManager.getLogger(BlogController.class);

    @Autowired
    public BlogController(LabelMapper labelMapper, UserService userService, BlogService blogService, CommentService commentService, UploadImage uploadImage) {
        this.labelMapper = labelMapper;
        this.userService = userService;
        this.blogService = blogService;
        this.commentService = commentService;
        this.uploadImage = uploadImage;
    }


    @PostMapping("/add")
    public String addBlog(Blogs blog, @RequestPart("blogImgSrc") MultipartFile blogImgSrc) throws IOException {

        String image = uploadImage.upload(blogImgSrc);

        // 获取本用户
        UserVO userVO = (UserVO) MyContextUtil.getSession().getAttribute("userVO");

        Users user = userVO.getUser();
        blog.setUserId(user.id);
        blog.setImage(image);
        Date date = new Date();
        System.out.println(date);
        blog.setCreateTime(date);
        blog.setTitle(blog.getTitle().trim());
        blog.setPostScript(blog.getPostScript().trim());
        blog.setContent(blog.getContent().trim());
        blogService.save(blog);

        return "redirect:/index/list";
    }


    @GetMapping("/pageList")
    public String pageList(@RequestParam("pageNo") Integer pageNo,
                           BlogListDTO blogListDTO, Model model) {

        List<Labels> labels = labelMapper.selectList(null);

        Page<BlogDetailVO> page = new Page<>(pageNo * 2 - 1, 3);
        blogService.selectAllByActive(page, blogListDTO);

        model.addAttribute("blog1", page.getRecords());

        Page<BlogDetailVO> page1 = new Page<>(pageNo * 2L, 3);
        blogService.selectAllByActive(page1, blogListDTO);

        model.addAttribute("blog2", page1.getRecords())
                .addAttribute("labeled", blogListDTO.getBlogLabel())
                .addAttribute("blogKey", blogListDTO.getBlogKey());

        // 设置分页与计算分页信息
        PageUtil pageUtil = new PageUtil(Math.toIntExact(page.getTotal()), pageNo, 3);
        List<Integer> pageNumList = pageUtil.countPreAndSufNo();

        // 查询hot排行榜
        getBlogRange(model);

        model.addAttribute("pageNo", pageUtil.getCurrentPageNo())
                .addAttribute("totalPage", pageUtil.getTotalPageNo())
                .addAttribute("pageName", "list")
                .addAttribute("labels", labels)
                .addAttribute("pageNumList", pageNumList);

        return "list";
    }

    @GetMapping("/myBlogPageList")
    public String myBlogPageList(@RequestParam("pageNo") Integer pageNo,
                                 BlogListDTO blogListDTO, Model model) {
        List<Labels> labels = labelMapper.selectList(null);

        Page<BlogDetailVO> page = new Page<>(pageNo, 15);

        blogService.selectAllByActive(page, blogListDTO);

        // 设置分页与计算分页信息
        PageUtil pageUtil = new PageUtil(Math.toIntExact(page.getTotal()), pageNo, 15);
        List<Integer> pageNumList = pageUtil.countPreAndSufNo();

        // 查询hot排行榜
        getBlogRange(model);

        model.addAttribute("blogs", page.getRecords())
                .addAttribute("blogKey", blogListDTO.getBlogKey())
                .addAttribute("labeled", blogListDTO.getBlogLabel())
                .addAttribute("pageNo", pageNo)
                .addAttribute("totalPage", pageUtil.getTotalPageNo())
                .addAttribute("labels", labels)
                .addAttribute("pageNumList", pageNumList)
                .addAttribute("pageName", "myList");

        return "myList";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model) {

        // 查询出博客详细信息
        BlogDetailVO blogDetailVO = blogService.selectOneById(id);

        // 查询该博客 博主的头像
        Users user = userService.getById(blogDetailVO.getUserId());

        // 把评论查询出来
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        wrapper.eq("blog_id", id);
        List<Comments> list = commentService.list(wrapper);

        model.addAttribute("blog", blogDetailVO)
                .addAttribute("comList", list)
                .addAttribute("blogger", user);

        // 查询hot排行榜
        getBlogRange(model);

        UpdateWrapper<Blogs> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("views", blogDetailVO.getViews() + 1)
                .eq("id",id);
        blogService.update(updateWrapper);

        return "detail";
    }


    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {

        // 获取本用户
        UserVO userVO = (UserVO) MyContextUtil.getSession().getAttribute("userVO");

        QueryWrapper<Blogs> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        blogService.remove(wrapper);

        return "redirect:/blog/myBlogPageList?blogKey=&blogLabel=0&pageNo=1&userId=" + userVO.getUser().id;
    }


    public void getBlogRange(Model model) {

        QueryWrapper<Blogs> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "likes").orderByDesc("likes");
        Page<Blogs> page = new Page<>(1, 5);

        blogService.page(page, wrapper);
        model.addAttribute("likeRange", page.getRecords());


        QueryWrapper<Blogs> wrapper1 = new QueryWrapper<>();
        wrapper1.select("id", "title", "views").orderByDesc("views");

        blogService.page(page, wrapper1);
        model.addAttribute("viewRange", page.getRecords());
    }

}
